<template>
  <div class="call-center-workbench-robot" v-loading.fullscreen.lock="loadingListData" >
    <div class="left">
      <div class="current-header">
        <span>当前通话</span>   
        <el-button v-if="haveRing" type="danger" @click="hangUpCall">挂断</el-button>
      </div>
      <el-card v-if="callCenterData.phone && haveRing && callCenterData.isShowCurrentCall" class="current-card">
        <div class="current-item">
          <div class="item">
            <p>{{callCenterData.name ? `${callCenterData.name} ${callCenterData.phone}` : '未知联系人'}} </p>
            <span>{{ ringTime }}</span>
          </div>
          <div class="item">
            <p style="margin-bottom:0">
              {{ callCenterData.name }}
            </p>
            <i class="iconfont" style="color:#55B7B4" :class="query.callType === 1 ? 'icon-qudian' : 'icon-laidian'"></i>
          </div>
        </div>
      </el-card>
      <el-card class="history-card">
        <div slot="header">今日历史通话（{{recordListPage.total}}）</div>
        <div v-if="recordListPage.list.length != 0">
          <div v-for="(item,index) in recordListPage.list" :key="item.id" class="history-item" 
               :class="{'item-active': item.id == activeLinkId,'item-hover':index==hoverIndex}"
               @click="handleHistoryItem(item,index)"
               @mouseover="hoverIndex = index"
               @mouseout="hoverIndex = -1">
            <i v-if="hoverIndex===index && item.id != activeLinkId" class="iconfont icon-fe-close" @click.stop="delHistoryItem(index,item)"></i>
            <div class="current-item">
              <div class="item">
                <p>{{item.linkmanName}} {{item.dialPhone}}</p>
                <span>{{item.ring |fmt_short_time}}</span>
              </div>
              <div class="item">
                <p style="margin-bottom:0;color:#999;">{{item.customerName}}</p>
                <i class="iconfont" :class="item.callType == '1' ? 'icon-qudian' : 'icon-laidian'"></i>
              </div>
            </div>

          </div>
          <div class="call-center-list-footer">
            <button class="call-center-list-footer-more" @click="getMore" v-if="moreShow && !loading">加载更多</button>
            <div v-if="loading">正在加载...</div>
            <div v-if="!moreShow && !loading">
              <span class="call-center-list-footer-line"></span>
              <span class="call-center-list-footer-text">没有更多数据</span>
              <span class="call-center-list-footer-line"></span>
            </div>
          </div>
        </div>
        <div class="call-center-list-footer" v-else-if="recordListPage.list.length == 0 && !loading">暂无数据</div>
        <div class="call-center-list-footer" v-else>正在加载...</div>
      </el-card>
    </div>
    <div class="main">
      <!-- <base-tabbar :tabs="tabs" v-model="currTab"></base-tabbar>
      <component :is="currTab" :item="item" :key="item.id"></component> -->
      <contact-info :item="item" :key="item.id"></contact-info>
    </div>
    <div class="right">
      <h4 style="font-size: 16px;margin-bottom: 20px;padding-top: 8px;fon">服务记录</h4>
      <service-record-sobot :item="item" :key="item.id"></service-record-sobot>
    </div>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'
import * as CallCenterApi from '@src/api/CallCenterApi'
import ContactInfo from './ContactInfoSobot.vue'
import { parse } from '@src/util/querystring';
import Page from '@model/Page';
import ServiceNotes from "@src/modules/im/imDetail/ServiceNotes.vue";
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
/* util */
import CallCenterZhiChiUtil from '@src/util/callcenter/CallcenterZhiChi.ts'
import ServiceRecordSobot from './ServiceRecordSobot.vue';
import { getRootWindow } from '@src/util/dom';

let callInterval;
export default {
  name: 'workbench-sobot',
  mixins: [ThemeMixin],
  data() {
    return {
      isOpenData,
      loading: false,
      params: {
        pageSize: 10,
        pageNum: 1,
      },
      recordListPage: new Page(),
      loadingListData: false,
      query: {},
      ringTime:'00:00',
      unkonwn: false,
      hoverIndex: -1, // 菜单hover索引
      activeLinkId: 0, // 当前激活的菜单id
      historyList: [],
      item: {},
      haveRing:false,
      ringState:null,
    }
  },
  computed: {
    moreShow () {
      return this.recordListPage.hasNextPage;
    },
    rootWindow() {
      return getRootWindow(window)
    },
    callCenterData() {
      return this.rootWindow?.getZhiChiCallCenterData() || {}
    }
  },
  mounted() {
    this.query = parse(window.location.search) || {};
    
    if (this.callCenterData.callId && this.callCenterData.phone) {
      
      if (this.callCenterData.isOnCall && this.callCenterData.isShowCurrentCall) {
        
        let callSec = 0;
        
        callInterval = setInterval(()=>{
          callSec ++;
          this.getCallTime(callSec)
        }, 1000);
        
      } else {
        callInterval && clearInterval(callInterval)
        callInterval = null
      }
      
      // 说明是websocket过来的 获取联系人信息 
      // this.item = { id: this.query.id, dialPhone:this.query.callPhone || '', dialCount:this.query.dialCount || 0} 
    }
    // console.info('query::', this.query);
    // this.$eventBus.$on('callcenter-workbench.select_tab', this.selectTab)
    
    this.getHistoryList().then(list => {
      if (
        this.callCenterData.callId 
        && this.callCenterData.phone
        && this.callCenterData.isOnCall
      ) {
        this.item = this.recordListPage.list[0] || {}
        this.recordListPage.list = this.recordListPage.list.slice(1)
      }
    })
    
    // 获取当前的通话状态
    this.ringState = setInterval(()=>{
      
      const zhiChiCallCenterData = window.parent?.getZhiChiCallCenterData() || {}
      this.haveRing = zhiChiCallCenterData.isOnCall;
      
    }, 1000)
  },
  beforeDestroy() {
    callInterval && clearInterval(callInterval)
    callInterval = null
    this.ringState = null;
  },
  methods: {
    async hangUpCall(){
      try {
        const callCenterData = window.parent.getZhiChiCallCenterData()
        const callId = callCenterData?.callId
        
        CallCenterZhiChiUtil.agentHangUp(callId)
        
        setTimeout(() => {
          window.parent.outSideGetAgent()
        }, 2000)
        
        window.location.reload()
        
      } catch(error) {
        console.error(error);
      }
    },
    async getMore () {
      try {
        this.params.pageNum++;
        this.loading = true;
        let recordListPage = await CallCenterApi.getZhiChiTodayCallRecordList(this.params);
        if(recordListPage.code == 0) {
          this.recordListPage.merge(Page.as(recordListPage.result));
        }
        this.loading = false;
      } catch(error) {
        console.error(error);
      }
    },
    getCallTime(sec){
      const HOUR_SEC = 60 * 60;
      const MIN_SEC = 60;
      let hour = sec / HOUR_SEC >> 0;
      sec = sec % HOUR_SEC;
      let min = sec / MIN_SEC >> 0;
      sec = sec % MIN_SEC;
      hour = hour > 0 && hour < 10 ? `0${ hour }` : hour;
      min = min < 10 ? `0${ min }` : min;       
      sec = sec < 10 ? `0${ sec }` : sec;
      // console.info('temp:', hour == 0 ? `${ min }:${ sec }` : `${ hour }:${ min }:${ sec }`);
      this.ringTime = hour == 0 ? `${ min }:${ sec }` : `${ hour }:${ min }:${ sec }`;
    },
    // 今日通话记录
    async getHistoryList(){
      return new Promise(async (resolve, reject) => {
        try {
          
          this.recordListPage.list = [];
          this.params.pageNum = 1;
          this.loading = true;
          
          let recordListPage = await CallCenterApi.getZhiChiTodayCallRecordList(this.params);
          
          if (recordListPage.code == 0) {
            
            this.recordListPage.merge(Page.as(recordListPage.result));
            
            if (this.recordListPage.list.length) {
              this.item = this.recordListPage.list[0]
              this.activeLinkId = this.item.id
            }
            
          }
          
          this.loading = false;
          
          resolve(this.recordListPage.list)
          
        } catch(error) {
          console.error(error);
        }
      })
    },
    handleHistoryItem(item, index) {
      this.activeLinkId = item.id
      this.item = item
    },
    async delHistoryItem(index, item) {
      try {
        const {code, message} = await CallCenterApi.deleteTodayCallRecord({id:item.id})
        if (code !== 0) return this.$platform.notification({
          title: '删除失败',
          message: message || '',
          type: 'error',
        })
        this.recordListPage.list.splice(index, 1)
        this.$platform.notification({
          title: '删除成功',
          type: 'success',
        })
      } catch (e) {
        console.error(e)
      }
    },
  },
  components: {
    ServiceNotes,
    [ContactInfo.name]: ContactInfo,
    [ServiceRecordSobot.name]: ServiceRecordSobot
  }
}
</script>

<style lang="scss">
.el-cascader-menus .el-cascader-menu__item{
  padding: 8px 15px;
  display: flex;
  line-height: 21px;
}
.el-cascader-menus .el-cascader-menu__item div{
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  max-width: 120px!important;
}
.item-hover {
  background-color: #fafafa;
}
.item-active {
  // 链接菜单激活样式
  background-color: #f5f5f5;
  border-left: 3px solid #55B7B4;
}

.call-center-workbench-robot {
  h4 {
    font-size: 16px;
    font-weight: 600;
  }
  display: flex;
  padding: 10px;
  position: relative;
  box-sizing: border-box;
  min-height: 100vh;
  max-width: 100vw;
  .left {
    width: 20%;
    min-width: 270px;
    .el-card__header {
      padding: 13px 20px;
    }
    .current-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 20px;
      border-bottom: 1px solid #ebeef5;
      box-sizing: border-box;
      background: #fff;
      font-size: 16px;
      color: #051A13;
      height: 50px;
      font-weight: 600;
    }
    .current-card {
      box-shadow: 0 0 0 0;
      border: none;
      .el-card__body {
        padding: 10px 15px;
        background: #f5f5f5;
        border-left: 3px solid $color-primary;
        .current-item {
          .item {
            display: flex;
            justify-content: flex-end;
            p {
              flex: 1;
              margin-bottom: 4px;
            }
            i,
            span {
              color: #999;
            }
          }
        }
      }
    }
    .history-card {
      box-shadow: 0 0 0 0;
      border-radius: 0 0 4px 4px;
      .el-card__body {
        overflow: auto;
        max-height: 800px;
        padding: 0;
        .history-item {
          padding: 12px 15px;
          display: flex;
          align-items: center;
          border-bottom: 1px solid #e0e1e2;
          cursor: pointer;

          .icon-fe-close {
            margin-right: 10px;
          }
          .current-item {
            flex: 1;
            .item {
              display: flex;
              justify-content: space-between;
              p {
                margin-bottom: 4px;
              }
              i,
              span {
                color: #999;
              }
            }
          }
        }
      }
      .call-center-list-footer {
        text-align: center;
        margin-top: 10px;
        height: 30px;
        line-height: 30px;
        color: #8C8989;
      }
      .call-center-list-footer-more {
        margin: 0;
        padding: 0;
        outline: none;
        border: none;
        background: none;
        color: #8C8989;
        &:hover {
          color: #55B7B4;
        }
      }
      .job-notification-dividing-line {
        width: 2px;
        height: 15px;
        background: #fff;
        position: absolute;
        right: 113px;
        top: 28px;
        z-index: 100;
      }
      .call-center-list-footer-line {
        position: relative;
        bottom: 4px;
        display: inline-block;
        background: #D0D0D0;
        height: 1px;
        width: 18px;
      }
      .call-center-list-footer-text {
        padding: 0 16px;
      }
    }

    .el-card__header {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

  }

  .main {
    flex: 1;
    background: #fff;
    border-right: 1px solid #f5f5f5;
  }
  .right {
    overflow: auto;
    /* max-height: 100vh; */
    background: #ffffff;
    width: 400px;
    min-width: 330px;
    padding: 10px;
    .item {
      margin-bottom: 10px;
      border-bottom: 1px solid #f5f5f5;
      .item-title {
        display: flex;
        justify-content: space-between;
        h4{
          font-size: 14px;
          margin-bottom: 10px;
          margin-left: 8px;
          font-weight:600;
        }
      }
      .item-header {
        display: flex;
        align-items: center;
        p {
          flex: 1;
          margin-bottom: 10px;
          margin-left: 8px;
        }
      }
      .item-isDelete {
        display: flex;
        justify-content: space-between;
        color: #fb602c;
        height: 42px;
        font-size: 14px;
        line-height: 42px;
        .delete-time {
          color: #666;
          font-size: 12px;
        }
      }
      .item-content {
        padding: 5px;
        p {
          padding: 10px 2px;
          color: #737f7b;
        }
        .el-tag--small {
          overflow: hidden;
        }
        .sort {
          width: 90px;
          white-space: nowrap;
          text-overflow: ellipsis;
          margin-right: 8px;
        }
      }
    }
    .el-textarea__inner{
      padding: 5px 10px;
    }

    .el-cascader__label{
      max-width: 160px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
</style>